package  image
{
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	
	/**
	 * ...
	 * @author dustfall
	 * image to bytearray or inverse
	 * 
	 * 
	 */
	public class Image2Byte 
	{
		
		public function Image2Byte() 
		{
			
		}
		
		public static function baToBm(ba:ByteArray):Bitmap{
			if (ba == null) {
				return null;
			}
			var bmd:ByteArray = ba;
			bmd.position = bmd.length - 2;
			var iw:int = bmd.readShort();
			bmd.position = bmd.length - 4;
			var ih:int = bmd.readShort();
			var copyBmp:BitmapData = new BitmapData(iw, ih, true);
			
			bmd.position = 0;
			for (var i:uint = 0; i < ih; i++) {
				for (var j:uint = 0; j < iw; j++) {
					copyBmp.setPixel(j, i, bmd.readUnsignedInt());
				}
			}
			
			var bm:Bitmap = new Bitmap(copyBmp);
			return bm;
		}
		
		public static function bmdToBa(bmd:BitmapData):ByteArray
		{
			var iw:uint = bmd.width;
			var ih:uint = bmd.height;
			
			var pixels:ByteArray = bmd.getPixels(new Rectangle(0, 0, iw, ih));
			pixels.writeShort(ih);
			pixels.writeShort(iw);
			return pixels;
		}
		
	}

}